package com.gewu.pm.ui.dialog;

import android.content.Context;
import android.content.res.Resources;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gewu.pm.R;
import com.gewu.pm.aop.SingleClick;
import com.gewu.pm.app.AppAdapter;
import com.hjq.base.BaseAdapter;
import com.hjq.base.BaseDialog;

import java.util.List;

/**
 * 通用选择列表弹窗
 * 
 * 功能：
 * 1. 支持传入 List<String> 数据
 * 2. 支持单选/多选模式
 * 3. 高度范围：最小屏幕1/3，最大屏幕2/3
 */
public final class SelectionListDialog {

    public static final class Builder
            extends BaseDialog.Builder<Builder>
            implements BaseDialog.OnShowListener, BaseDialog.OnDismissListener {

        private OnListener mListener;

        private final TextView mCancelView;
        private final TextView mTitleView;
        private final TextView mConfirmView;
        private final RecyclerView mRecyclerView;

        private final SelectionAdapter mAdapter;

        /** 当前选中的项（单选模式） */
        private String mSelectedItem = null;
        /** 当前选中的位置（单选模式） */
        private int mSelectedPosition = -1;
        /** 是否多选模式 */
        private boolean mMultiSelect = false;

        public Builder(Context context) {
            super(context);
            setContentView(R.layout.selection_list_dialog);
            setWidth(WindowManager.LayoutParams.MATCH_PARENT);
            setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
            setGravity(android.view.Gravity.BOTTOM);

            mCancelView = findViewById(R.id.tv_cancel);
            mTitleView = findViewById(R.id.tv_title);
            mConfirmView = findViewById(R.id.tv_confirm);
            mRecyclerView = findViewById(R.id.rv_list);

            setOnClickListener(mCancelView, mConfirmView);

            mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
            mAdapter = new SelectionAdapter(getContext(), this);
            mRecyclerView.setAdapter(mAdapter);

            addOnShowListener(this);
            addOnDismissListener(this);
        }

        /**
         * 设置标题
         */
        public Builder setTitle(String title) {
            mTitleView.setText(title);
            return this;
        }

        /**
         * 设置数据列表
         */
        public Builder setDataList(List<String> dataList) {
            mAdapter.setData(dataList);
            
            // 限制高度范围：最小1/3屏幕，最大2/3屏幕
            limitMaxHeight();
            
            return this;
        }

        /**
         * 设置默认选中项
         */
        public Builder setDefaultSelection(String defaultItem) {
            int position = mAdapter.getData().indexOf(defaultItem);
            if (position != -1) {
                mSelectedItem = defaultItem;
                mSelectedPosition = position;
                mAdapter.setSelectedPosition(position);
            }
            return this;
        }

        /**
         * 设置默认选中位置
         */
        public Builder setDefaultSelection(int position) {
            if (position >= 0 && position < mAdapter.getCount()) {
                mSelectedItem = mAdapter.getItem(position);
                mSelectedPosition = position;
                mAdapter.setSelectedPosition(position);
            }
            return this;
        }

        /**
         * 限制高度：最小屏幕1/3，最大屏幕2/3
         */
        private void limitMaxHeight() {
            DisplayMetrics displayMetrics = Resources.getSystem().getDisplayMetrics();
            int screenHeight = displayMetrics.heightPixels;
            int maxHeight = screenHeight * 2 / 3;
            int minHeight = screenHeight / 3;
            
            // 测量RecyclerView实际需要的高度
            mRecyclerView.post(() -> {
                mRecyclerView.measure(
                    View.MeasureSpec.makeMeasureSpec(mRecyclerView.getWidth(), View.MeasureSpec.EXACTLY),
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
                );
                
                int actualHeight = mRecyclerView.getMeasuredHeight();
                
                // 限制高度范围：最小1/3屏幕，最大2/3屏幕
                ViewGroup.LayoutParams params = mRecyclerView.getLayoutParams();
                if (actualHeight > maxHeight) {
                    // 超过最大高度，限制为最大高度
                    params.height = maxHeight;
                } else if (actualHeight < minHeight) {
                    // 小于最小高度，设置为最小高度
                    params.height = minHeight;
                } else {
                    // 在范围内，使用实际高度
                    params.height = actualHeight;
                }
                mRecyclerView.setLayoutParams(params);
            });
        }

        /**
         * 选择项（单选模式）
         */
        void onItemSelected(String item, int position) {
            mSelectedItem = item;
            mSelectedPosition = position;
        }
        
        /**
         * 获取是否多选模式
         */
        boolean isMultiSelect() {
            return mMultiSelect;
        }
        
        /**
         * 设置是否多选模式
         */
        public Builder setMultiSelect(boolean multiSelect) {
            mMultiSelect = multiSelect;
            return this;
        }

        public Builder setListener(OnListener listener) {
            mListener = listener;
            return this;
        }

        @SingleClick
        @Override
        public void onClick(View view) {
            int viewId = view.getId();
            if (viewId == R.id.tv_cancel) {
                dismiss();
                if (mListener != null) {
                    mListener.onCancel(getDialog());
                }
            } else if (viewId == R.id.tv_confirm) {
                if (mMultiSelect) {
                    // 多选模式：收集所有选中的项
                    String result = mAdapter.collectSelected();
                    
                    if (android.text.TextUtils.isEmpty(result)) {
                        Toast.makeText(getContext(), "请先选择", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    
                    dismiss();
                    if (mListener != null) {
                        // 多选模式返回用顿号分隔的字符串，position为-1
                        mListener.onSelected(getDialog(), result, -1);
                    }
                } else {
                    // 单选模式
                    if (mSelectedItem == null) {
                        Toast.makeText(getContext(), "请先选择", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    dismiss();
                    if (mListener != null) {
                        mListener.onSelected(getDialog(), mSelectedItem, mSelectedPosition);
                    }
                }
            }
        }

        @Override
        public void onShow(BaseDialog dialog) {
        }

        @Override
        public void onDismiss(BaseDialog dialog) {
        }
    }

    /**
     * 选择列表适配器
     */
    private static final class SelectionAdapter extends AppAdapter<String>
            implements BaseAdapter.OnItemClickListener {

        private final Builder mBuilder;
        /** 单选模式：选中的位置 */
        private int mSelectedPosition = -1;
        /** 多选模式：选中的项列表 */
        private final java.util.ArrayList<String> mSelectedItems = new java.util.ArrayList<>();

        private SelectionAdapter(Context context, Builder builder) {
            super(context);
            mBuilder = builder;
            setOnItemClickListener(this);
        }

        void setSelectedPosition(int position) {
            mSelectedPosition = position;
            notifyDataSetChanged();
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new ItemViewHolder();
        }

        @Override
        public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
            String selectedItem = getItem(position);
            
            if (mBuilder.isMultiSelect()) {
                // 多选模式：切换选中状态
                if (mSelectedItems.contains(selectedItem)) {
                    mSelectedItems.remove(selectedItem);
                } else {
                    mSelectedItems.add(selectedItem);
                }
                notifyItemChanged(position);
            } else {
                // 单选模式：记录旧的选中位置
                int oldPosition = mSelectedPosition;
                
                // 更新选中状态
                mSelectedPosition = position;
                
                // 刷新旧的和新的选中项
                if (oldPosition != -1 && oldPosition != position) {
                    notifyItemChanged(oldPosition);
                }
                notifyItemChanged(position);

                // 回调
                mBuilder.onItemSelected(selectedItem, position);
            }
        }
        
        /**
         * 收集选中的项（多选模式）
         * @return 用"、"分隔的选中项
         */
        String collectSelected() {
            return android.text.TextUtils.join("、", mSelectedItems);
        }

        private final class ItemViewHolder extends AppAdapter<?>.ViewHolder {
            private final TextView mTextView;
            private final CheckBox mRadioCheckBox;

            private ItemViewHolder() {
                super(R.layout.selection_list_item);
                mTextView = findViewById(R.id.tv_item_text);
                mRadioCheckBox = findViewById(R.id.cb_radio);
                
                // ❌ 禁止手动设置点击事件（BaseAdapter会自动处理）
                // getItemView().setOnClickListener(v -> onItemClick(getViewHolderPosition()));
                
                // ✅ BaseAdapter 会在 setOnItemClickListener() 后自动给 itemView 设置点击监听
            }

            @Override
            public void onBindView(int position) {
                String item = getItem(position);
                mTextView.setText(item);
                
                // 更新选中状态（CheckBox使用setChecked()）
                boolean isSelected;
                if (mBuilder.isMultiSelect()) {
                    // 多选模式：检查是否在选中列表中
                    isSelected = mSelectedItems.contains(item);
                } else {
                    // 单选模式：检查位置是否匹配
                    isSelected = position == mSelectedPosition;
                }
                mRadioCheckBox.setChecked(isSelected);
            }
        }
    }

    /**
     * 选择监听器
     */
    public interface OnListener {
        /**
         * 选中回调
         * 
         * @param dialog 弹窗实例
         * @param selectedItem 选中的项
         * @param position 选中的位置
         */
        void onSelected(BaseDialog dialog, String selectedItem, int position);

        /**
         * 取消回调（可选）
         */
        default void onCancel(BaseDialog dialog) {
        }
    }
}

